<template>
  <el-dialog append-to-body :close-on-click-modal="false" v-if="isCommonModalTemplate" :title="option.modalTitle" :visible.sync="isCommonModalTemplate" width="60%" top="5vh">
    <!-- 副标题 -->
    <div class="common-modal-sub-title" v-if="option.subTitle && option.subTitle.show">
      <i :class="[option.subTitle.icon || 'el-icon-vertical-bar', 'avue-group__icon']"></i>
      <h1 class="avue-group__title">{{ option.subTitle.name }}</h1>
    </div>
    <avue-crud
      ref="crud"
      :table-loading="loading"
      :data="data"
      :option="tableOption"
      @search-change="searchChange"
      @search-reset="searchReset"
      :page.sync="page"
      @on-load="onLoad"
      @selection-change="selectionChange"
      @row-click="rowClick"
      @row-dblclick="rowDbclick"
      @current-change="currentChange"
      @size-change="sizeChange"
      @select="select"
      @refresh-change="refreshChange"
      @tree-load="treeLoad"
    >
      <template slot="menuLeft">
        <el-button :type="activeBtn === 'firstBtn' ? 'primary' : ''" size="small" @click="handleSelectProduct">Bom半成品</el-button>
        <el-button :type="activeBtn === 'secondBtn' ? 'primary' : ''" size="small" @click="handleSelectMaterial">物料在制品</el-button>
      </template>
    </avue-crud>
    <div slot="footer" class="dialog-footer" v-if="option.rowSelectionType != 'single'">
      <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitForm">保存</el-button>
      <el-button size="small" icon="el-icon-circle-close" @click="isCommonModalTemplate = false">取消</el-button>
    </div>
    <div slot="footer" class="dialog-footer close" v-if="option.showDetails">
      <el-button size="small" icon="el-icon-circle-close" @click="isCommonModalTemplate = false">关 闭</el-button>
    </div>
  </el-dialog>
</template>
<script>
import request from '@/router/axios';
export default {
  name: 'partMasterModel',
  props: {
    option: {
      type: Object,
      default: () => ({})
    }
  },
  components: {},
  watch: {
    isCommonModalTemplate: function (val) {
      if (!val) {
        this.$emit('newKey', '');
        this.tableOption.option = '';
        this.query = {};
        this.tableOption.isDefaultLoad = true;
      }
    }
  },
  data() {
    return {
      isCommonModalTemplate: false, //模态框是否显示
      query: {}, // 外界传来的参数集合
      method: 'get',
      url: '',
      activeBtn: 'firstBtn',
      tableOption: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        border: true, //表格外框线是否显示
        stripe: true, //表格是否显示条纹
        header: true, //表格头部是否显示
        index: true, //表格数据序号
        indexLabel: '序号',
        page: false, //表格分页是否显示
        noPageParams: false, // true时不分页时不传参total和pageSize
        addBtn: false, //新增按钮是否显示
        menu: false, //表格操作栏是否显示
        refreshBtn: true, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        // searchBtn: false
        searchMenuSpan: 6, //搜索按钮所占宽度
        searchMenuPosition: 'right', //搜索按钮位置
        column: [], //表格列配置
        selection: false, //表格是否多选
        reserveSelection: false, //表格是否分页多选
        rowKey: 'id',
        searchShow: true,
        isFilter: false, //是否对数据进行过滤
        query: {},
        subTitle: {
          // 表格顶部展示子标题
          show: false,
          icon: '',
          name: ''
        },
        filterOption: {
          //表格数据过滤
          isFilter: false,
          prop: '',
          data: [] //过滤的数据
        },
        selectOption: {
          isMark: false, //是否标记选择项
          data: [], //标记的数据
          prop: '', //对应列表的属性
          selectedData: []
        }
      }, //表格属性
      // 分页器配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      }, //表格分页
      selectedRows: [], //表格选中行数据
      data: [], //表格数据
      loading: false,
      titleInfo: '',
      filterOption: {},
      selectOption: {},
      isDefaultLoad: true //是否默认加载数据
    };
  },

  created() {},

  mounted() {},

  methods: {
    /**
     *显示模态框
     */
    showModal() {
      //赋值已选中的数据
      setTimeout(() => {
        this.tableOption.column = this.option.columnDefs;
        this.titleInfo = this.option.titleInfo;
        this.tableOption.page = this.option.isPage;
        this.tableOption.noPageParams = this.option.noPageParams;
        this.tableOption.rowKey = this._get(this.option, 'rowKey', 'id');
        // 浅拷贝crud配置项  this.tableOption
        this._assgin(this.tableOption, this.option);
        delete this.tableOption.readonly; //拷贝将readonly属性拷贝进去导致搜索输入框无法输入，readonly属性原作用于禁用表单双击
        this.filterOption = this.tableOption.filterOption;
        this.selectOption = this.tableOption.selectOption;
        this.method = this.tableOption.method;
        this.isDefaultLoad = this._get(this.tableOption, 'isDefaultLoad', true); //表格是否默认加载数据
        if (this.selectOption.isMark && this._get(this.selectOption, 'selectedData', []).length > 0) {
          this.selectedRows = this.selectOption.selectedData;
        }

        // 关闭分页功能时将pageSize=10000;
        if (!this.tableOption.page) {
          this.page.total = 0;
          this.page.pageSize = 10000;
        } else {
          this.page.total = 0;
          this.page.currentPage = 1;
          this.page.pageSize = 15;
        }
        this._forEach(this.tableOption.columnDefs, (item) => {
          if (this._get(item, 'searchValue', '')) {
            this.query[item.prop] = item.searchValue;
          }
        });
        // 外界接口参数
        // this.query = this.tableOption.query;
        if (this.option.rowSelectionType === 'single') {
          this.tableOption.selection = false;
        } else {
          this.tableOption.selection = true;
          this.tableOption.reserveSelection = true;
        }
        this.isCommonModalTemplate = true;
      }, 500);
    },

    /**
     * 首次加载表格
     */
    onLoad(page, params = {}) {
      // if (!this.tableOption.page) {
      //     this.page = {};
      // } else {
      //     // this.page.total = 1;
      //     this.page.currentPage = 1;
      // }
      this.createRowData(page, Object.assign(params, this.query, this.tableOption.query));
    },

    /**
     * 多选事件
     */
    selectionChange(list) {
      // this.$message.success('选中的数据' + JSON.stringify(list));
      if (!this.selectOption.isMark) {
        this.selectedRows = list;
      }
      if (this.selectOption.isMark && !this.tableOption.page) {
        this.selectedRows = list;
      }
    },

    /**
     * 单击事件
     */
    rowClick(row) {
      if (this.tableOption.selection && !this.selectOption.isMark) {
        this.$refs.crud.toggleRowSelection(row);
      }
    },

    /**
     * 双击事件
     */
    rowDbclick(row) {
      if (!this.option.readonly && this.option.rowSelectionType === 'single') {
        if (this.activeBtn === 'secondBtn') {
          row.partMasterId = row.id;
        }
        this.$emit('getSelectedRows', row, this.titleInfo);
        this.isCommonModalTemplate = false;
      }
    },
    /**
     * 改变当前页
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 改变当前页大小
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    /**
     * 隐藏模态框
     */
    hideModal() {
      this.isCommonModalTemplate = false;
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      //   this.tableOption.query = { ...this.query, ...params };
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    /**
     * 刷新
     */
    refreshChange() {
      this.onLoad(this.page);
    },
    /**
     * 搜索重置
     */
    searchReset() {
      //   this.tableOption.query = { ...this.query };
      this.query = {};
      if (this.option.noResetRequest) {
        this.data = [];
        this.page.total = 0;
        return;
      }
      this.onLoad(this.page);
    },
    /**
     * 标记选择项
     */
    markSelected(data) {
      let unselects = this._differenceWith(data, this.selectOption.data, (item1, item2) => {
        return item1[this.selectOption.prop] === item2;
      });
      let selects = this._differenceWith(data, unselects, (item1, item2) => {
        return item1[this.selectOption.prop] === item2[this.selectOption.prop];
      });
      selects.forEach((row) => {
        this.$nextTick(() => {
          this.$refs.crud.toggleRowSelection(row);
        });
      });
    },

    /*
     * 选择或取消当前行时
     */
    select(selection, row) {
      let selectedRows = this._cloneDeep(this.selectedRows);
      if (this.selectOption.isMark && this._get(this.selectOption, 'selectedData', []).length > 0 && this.tableOption.page) {
        this._forEach(selectedRows, (item, idx) => {
          if (this._get(item, this.selectOption.prop, '') === row[this.selectOption.prop]) {
            this._remove(this.selectedRows, (n) => {
              return n[this.selectOption.prop] === row[this.selectOption.prop];
            });
          }
        });

        let flag = selectedRows.every((item) => {
          return item[this.selectOption.prop] !== row[this.selectOption.prop];
        });
        if (flag) {
          this.selectedRows.push(row);
        }
      } else {
        this.selectedRows = selection;
      }
    },

    /**
     * 查询表格数据
     */
    createRowData(page, params) {
      if (this.isDefaultLoad) {
        this.loading = true;
        //是否默认加载数据

        let tableParams = {
          current: page.currentPage,
          size: page.pageSize,
          ...params
        };
        if (this.tableOption.noPageParams) {
          tableParams = {
            ...params
          };
        }
        request({
          url: this.url || this.option.url,
          method: this.method || 'get',
          params: tableParams
        }).then((res) => {
          const data = res.data.data;
          if (data.records) {
            if (this.option.isHaveRowKey === 'no') {
              this._forEach(data.records, (item) => {
                item.keyJson = JSON.stringify(item);
              });
            }
            this.data = data.records;
          } else {
            if (this.option.isHaveRowKey === 'no') {
              this._forEach(data, (item) => {
                item.keyJson = JSON.stringify(item);
              });
            }
            this.data = data;
          }

          let that = this;
          if (that.filterOption.isFilter) {
            //过滤选中的数据
            this.data = this._differenceWith(this.data, this.filterOption.data, (item1, item2) => {
              return item1[this.filterOption.prop] === item2;
            });
          }
          if (that.selectOption.isMark) {
            this.markSelected(this.data);
          }

          if (data.size) {
            this.page.total = data.total;
            this.page.pageSize = data.size;
          }
          setTimeout(() => {
            this.loading = false;
          }, 300);
        });
      } else {
        this.isDefaultLoad = true;
      }
    },
    handleSelectProduct() {
      this.url = '';
      this.activeBtn = 'firstBtn';
      this.page.currentPage = 1;
      this.page.pageSize = 15;
      this.$refs.crud.searchReset();
    },
    handleSelectMaterial() {
      this.activeBtn = 'secondBtn';
      this.url = '/api/mes-admin/part-master/page?semifinished=true';
      this.page.currentPage = 1;
      this.page.pageSize = 15;
      this.$refs.crud.searchReset();
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      return request({
        url: this.option.url,
        method: this.method || 'get',
        params: {
          parentId
        }
      }).then((res) => {
        resolve(res.data.data);
      });
    },
    /**
     * 提交选择行
     */
    submitForm() {
      if (this.option.isSingleChoice && this.selectedRows.length > 1) {
        this.$message({
          type: 'warning',
          message: '当前功能只能选中一条数据！'
        });
        return;
      }
      this.$emit('getSelectedRows', this.selectedRows, this.titleInfo);
      this.isCommonModalTemplate = false;
      // done();
    }
  }
};
</script>
<style lang="scss" scoped>
.el-form-item--small.el-form-item {
  margin-bottom: 0;
}
.common-modal-sub-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin: -10px 0;
}
.table-title {
  font-size: 16px;
  font-weight: bold;
  .mr10 {
    margin-right: 10px;
  }
}
</style>
